
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="padding: 36px">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="课程信息" />
          <el-step title="其他信息" />
          <el-step title="章程信息" />
        </el-steps>
        <div style="padding: 36px">
          <el-form v-show="active === 0" ref="courseForm" :model="courseForm" :rules="rules" label-width="120px">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="courseForm.name" style="width: 40%" placeholder="请输入课程名称" />
            </el-form-item>
            <el-form-item label="适用地区" prop="province">
              <el-select v-model="courseForm.province" remote filterable placeholder="请选择地区"
                :remote-method="remoteMethod" :loading="selectload" style="width: 40%" @change="selectRegion">
                <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程科目" prop="subject">
              <el-select v-model="courseForm.subject" filterable placeholder="请选择科目" style="width: 40%">
                <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程封面" prop="cover">
              <el-upload :headers="headers" class="avatar-uploader" :action="host + '/api/v1/public/uploadFile'"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <el-image v-if="courseForm.cover" :src="getMediaUrl(courseForm.cover)" class="upload-image" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程状态" prop="status">
              <el-switch v-model="courseForm.status" style="width: 40%" :active-value="1" :inactive-value="-1"
                active-text="上架" inactive-text="下架" />
            </el-form-item>
            <el-form-item label="课程价格" prop="price">
              <el-input-number v-model="courseForm.price" controls-position="right" placeholder="请输入课程价格"
                style="width: 40%" />
            </el-form-item>

            <el-form-item label="课程大纲" prop="outline">
              <el-row :gutter="3" style="margin-left: 0">
                <el-col v-for="(item, index) in courseForm.outline" :key="index" style="margin-bottom: 10px" :span="6">
                  <Pictures :url="getMediaUrl(item)" :index="index"
                    @deletefile="(file) => handleRemove(file, 'outline')" />
                </el-col>
                <el-col :span="6">
                  <el-upload :headers="headers" class="avatar-uploader" :action="host + '/api/v1/public/uploadFile'"
                    :show-file-list="false" :on-success="(res) => handleAvatarOutline(res, 'outline')"
                    :before-upload="beforeAvatarUpload">
                    <i class="el-icon-plus avatar-uploader-icon" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="课程简介" prop="introduction">
              <el-row :gutter="3" style="margin-left: 0">
                <el-col v-for="(item, index) in courseForm.introduction" :key="index" style="margin-bottom: 10px"
                  :span="6">
                  <Pictures :url="getMediaUrl(item)" :index="index"
                    @deletefile="(file) => handleRemove(file, 'introduction')" />
                </el-col>
                <el-col :span="6">
                  <el-upload :headers="headers" class="avatar-uploader" :action="host + '/api/v1/public/uploadFile'"
                    :show-file-list="false" :on-success="(res) => handleAvatarOutline(res, 'introduction')"
                    :before-upload="beforeAvatarUpload">
                    <i class="el-icon-plus avatar-uploader-icon" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                  </el-upload>
                </el-col>
              </el-row>
              <!-- <el-input v-model="courseForm.introduction" type="textarea" placeholder="请输入内容" :rows="2"
                style="width: 40%" /> -->
            </el-form-item>
            <el-form-item label="公告" prop="announcement">
              <el-input v-model="courseForm.announcement" type="textarea" placeholder="请输入内容" :rows="2" :maxlength="200"
                style="width: 40%" />
            </el-form-item>
            <el-form-item label="试听课程" prop="audition_link">
              <div v-if="courseForm.audition_link">
                <span style="cursor:pointer" @click="() => playVideo(courseForm.audition_link)">{{
                    courseForm.audition_course_name
                }}</span>
                <i class="el-icon-delete" style="margin-left: 10px;cursor:pointer"
                  @click="(event) => beforeRemove(event, courseForm.audition_course_name)" />
              </div>
              <el-progress v-else-if="loading" :text-inside="true" :stroke-width="15" :percentage="percentage"
                style="width: 40%" />
              <el-upload v-else :headers="headers" class="upload-demo" style="width: 40%" action
                :http-request="httpUpload" :show-file-list="false">
                <div v-if="!loading">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传mp4/wav文件</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>

          <el-form v-show="active === 1" ref="lecturerForm" :model="lecturerForm" :rules="rules" label-width="100px">
            <el-form-item label="教师姓名" prop="lecturer_id">
              <el-select v-model="lecturerForm.lecturer_id" style="width: 40%" filterable placeholder="请选择教师">
                <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="网课班级" prop="online_class_id">
              <el-select v-model="lecturerForm.online_class_id" style="width: 40%" filterable placeholder="请选择班级">
                <el-option v-for="item in networkClassList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="课程效期" prop="term_of_validity">
              <el-select v-model="lecturerForm.term_of_validity" style="width: 40%" placeholder="请选择有效期">
                <el-option v-for="item in effective" :key="item.value" :label="item.lable" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="是否设置面授" prop="is_bind_offline">
              <el-switch v-model="lecturerForm.is_bind_offline" :active-value="1" :inactive-value="0" active-text="是"
                inactive-text="否" />
            </el-form-item>

            <el-form-item label="是否为精品课" prop="is_boutique">
              <el-switch v-model="lecturerForm.is_boutique" :active-value="1" :inactive-value="-1" active-text="是"
                inactive-text="否" />
            </el-form-item>

            <el-form-item label="选择题库">
              <div style="width: 40%;height: 36px;border: 1px solid #e6ebf5;border-radius: 4px;padding-left: 14px;"
                @click="clickTopic('question_bank', questionBankNumber)">{{ questionBankNumber.length > 0 ?
                    `已选择：${questionBankNumber.length}` : null
                }}</div>
            </el-form-item>

            <el-form-item label="选择试卷">
              <div style="width: 40%;height: 36px;border: 1px solid #e6ebf5;border-radius: 4px;padding-left: 14px;"
                @click="clickTopic('examination', examinationNumber)">{{ examinationNumber.length > 0 ?
                    `已选择：${examinationNumber.length}` : null
                }}</div>
            </el-form-item>

            <el-form-item label="联系客服" prop="telephone">
              <el-input v-model="lecturerForm.telephone" style="width: 40%" placeholder="请输入号码" />
            </el-form-item>

            <el-form-item label="客服QQ号" prop="qq">
              <el-input v-model="lecturerForm.qq" style="width: 40%" placeholder="请输入QQ码" />
            </el-form-item>

            <el-form-item label="班主任联系" prop="contacts">
              <el-upload :headers="headers" class="avatar-uploader" :action="host + '/api/v1/public/uploadFile'"
                :show-file-list="false" :on-success="handleAvatarContacts" :before-upload="beforeAvatarUpload">
                <img v-if="lecturerForm.contacts" :src="getMediaUrl(lecturerForm.contacts)" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-form>

          <div v-show="active === 2">
            <div style="display: flex; justify-content: flex-end;">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addChapter">添加章节</el-button>
            </div>
            <div v-if="chapterData.length > 0">
              <Chapter v-for="(item, index) in chapterData" :key="index" :chapter-key="index" :chapter-item="item"
                :host="host" :headers="headers" @say="parentSay" @dialogVisible="addChapter" @getDetails="getDetails" />
            </div>
            <el-empty v-else :image-size="150" />
          </div>
          <div style="float:right">
            <el-button v-show="active !== 0" style="margin-top: 12px;" @click="lastStep">上一步</el-button>
            <el-button type="primary" style="margin-top: 12px;" @click="submitForm">{{ active === 2 ? '确认' : '下一步' }}
            </el-button>
          </div>
        </div>
      </el-card>

      <el-dialog title="添加章节" :visible.sync="visible" destroy-on-close @closed="onClosed">
        <el-form ref="form" :model="form" :rules="chapterRules" label-width="80px">
          <el-form-item label="章节名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="form.note" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitChapterForm">确 定</el-button>
        </div>
      </el-dialog>
      <Video :show-video="showVideo" :play-url="playUrl" @handleHideModal="handleHideModal" />
      <Topic :visible-topic="visibleTopic" :topic-type="topicType" :id-list="idList" @cancelTopic="cancelTopic"
        @submitFormTopic="submitFormTopic" />
    </template>
  </BasicLayout>
</template>

<script>
import {
  addCourse,
  getDetails,
  classList,
  getCity,
  editCourse,
  editChapter,
  addChapter,
  delChapter,
  getSubject,
  getSave
} from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
import { getLeacher } from '@/api/admin/sys-teacher'
import Chapter from './chapter'
import Pictures from '@/components/Pictures'
import Video from '@/components/Video'
import Topic from '@/components/Topic'
import { clients, getNowDate } from '@/utils/index'
export default {
  name: 'NetworkCourse',
  components: {
    Chapter,
    Pictures,
    Video,
    Topic
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      host: '',
      active: 0,
      flagchange: 0,
      lecturerchange: 0,
      isChange: false,
      courseId: null,
      courseForm: {
        cover: null,
        status: -1,
        outline: [],
        introduction: [],
        subject: null
      },
      lecturerForm: {
        contacts: null,
        term_of_validity: 1,
        is_bind_offline: 0,
        is_boutique: -1,
        course_type: 'online'
      },
      course_gift: [
        {
          gift_type: 'question_bank',
          obj_ids: ''
        },
        {
          gift_type: 'examination',
          obj_ids: ''
        }
      ],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '课程科目不能为空', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '上传课程封面', trigger: 'blur' }],
        status: [{ required: true, message: '选择课程状态', trigger: 'blur' }],
        price: [
          { required: true, message: '课程价格不能为空', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '课程简介不能为空', trigger: 'blur' }
        ],
        outline: [{ required: true, message: '上传课程大纲', trigger: 'blur' }],
        lecturer_id: [{ required: true, message: '选择教师', trigger: 'blur' }],
        online_class_id: [
          { required: true, message: '选择网课班级', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '上传班主任二维码', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '选择适用地区', trigger: 'blur' }
        ],
        term_of_validity: [
          { required: true, message: '有效期不能为空', trigger: 'blur' }
        ]
      },
      chapterRules: {
        name: [{ required: true, message: '输入章节名称', trigger: 'blur' }]
      },
      visible: false,
      form: {},
      chapterData: [],
      chapterKey: -1,
      teacherList: [],
      networkClassList: [],
      effective: [{ value: 1, lable: '一年' }],
      cityList: [],
      subjectList: [],
      selectload: false,
      showVideo: false,
      playUrl: '',
      visibleTopic: false,
      topicType: '',
      questionBankNumber: [],
      examinationNumber: [],
      idList: [],
      loading: false,
      percentage: 0
    }
  },
  watch: {
    courseForm: {
      deep: true,
      handler(val) {
        this.flagchange++
        if (this.flagchange > 2) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
        if (val.province) {
          getSubject({ province: val.province }).then(res => {
            this.subjectList = res?.data || []
          })
        }
      }
    },
    lecturerForm: {
      deep: true,
      handler(val) {
        this.lecturerchange++
        if (this.lecturerchange > 1) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
      }
    }
  },
  created() {
    this.host = process.env.VUE_APP_BASE_API
    getLeacher().then(res => {
      this.teacherList = res?.data || []
    })
    classList({ class_type: '网课' }).then(res => {
      this.networkClassList = res?.data || []
    })
    getCity().then(res => {
      this.cityList = res?.data || []
    })
    if (this.$route.params.id) {
      /** 获取课程详情 */
      this.courseId = this.$route.params && Number(this.$route.params.id)
      this.getDetails()
    }
    if (this.$route?.params?.jump_id === 'subject') {
      this.active = 2
    }
  },
  methods: {
    selectRegion(val) {
      this.courseForm.subject = null
      getSubject({ province: val }).then(res => {
        this.subjectList = res?.data || []
      })
    },
    getDetails() {
      getDetails(this.courseId).then(response => {
        const { data = {} } = response
        const courseInfor = {
          ...data?.step1,
          outline:
            data?.step1?.outline.length > 0
              ? data?.step1?.outline.split(',')
              : [],
          introduction:
            data?.step1?.introduction.length > 0
              ? data?.step1?.introduction.split(',')
              : []
        }
        this.courseForm = {
          ...courseInfor,
          price: courseInfor.price / 100
        }
        this.lecturerForm = data?.step2
        this.course_gift = data?.step2?.course_gift.length > 0 ? data?.step2?.course_gift : [
          {
            gift_type: 'question_bank',
            obj_ids: ''
          },
          {
            gift_type: 'examination',
            obj_ids: ''
          }
        ]
        this.questionBankNumber = data?.step2?.course_gift[0]?.obj_ids
          ? data?.step2?.course_gift[0]?.obj_ids.split(',').map(Number)
          : []
        this.examinationNumber = data?.step2?.course_gift[1]?.obj_ids
          ? data?.step2?.course_gift[1]?.obj_ids.split(',').map(Number)
          : []
        this.chapterData = data?.course_ware_json
      })
    },
    // 添加章节
    addChapter(value) {
      if (value.type === 'delete') {
        if (value?.chapterItem?.id) {
          this.$confirm('是否确认删除', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delChapter(value?.chapterItem?.id).then(res => {
              if (res.code === 200) {
                this.chapterData = this.chapterData?.filter(
                  (item, index) => index !== value?.chapterKey
                )
              }
            })
          })
          return
        }
        this.chapterData = this.chapterData?.filter(
          (item, index) => index !== value?.chapterKey
        )
      } else {
        this.visible = true
        if (value?.chapterItem) {
          this.form = value?.chapterItem
          this.chapterKey = value?.chapterKey
        }
      }
    },
    submitChapterForm() {
      this.$refs['form'].validate(valid => {
        if (valid && this.chapterKey === -1) {
          if (this.courseId) {
            addChapter({
              ...this.form,
              pid: 0,
              course_id: this.courseId
            }).then(res => {
              if (res.code === 200) {
                this.chapterData.push({
                  ...this.form,
                  id: res.data,
                  course_id: this.courseId,
                  children: []
                })
                this.visible = false
                this.chapterKey = -1
              }
            })
            return
          }
        } else if (valid && this.chapterKey !== -1) {
          if (this.form.id) {
            editChapter(this.form).then(response => {
              this.chapterData = this.chapterData.map((item, index) =>
                index === this.chapterKey
                  ? JSON.parse(JSON.stringify(this.form))
                  : item
              )
              this.visible = false
              this.chapterKey = -1
            })
          }
        }
      })
    },
    cancel() {
      this.visible = false
    },
    onClosed() {
      this.form = {}
      this.resetForm('form')
    },
    // 上一步
    lastStep() {
      if (this.active-- < 1) return (this.active = 0)
    },
    // 下一步
    submitForm() {
      this.flagchange = 0
      if (this.active === 0) {
        this.$refs['courseForm'].validate(courseValid => {
          if (courseValid) {
            this.active++
          } else {
            return
          }
        })
      } else if (this.active === 1) {
        this.$refs['lecturerForm'].validate(lecturerValid => {
          if (lecturerValid) {
            const payload = {
              step1: {
                ...this.courseForm,
                outline: this.courseForm.outline.toString(),
                introduction: this.courseForm.introduction.toString(),
                price: this.courseForm.price * 100
              },
              step2: {
                ...this.lecturerForm,
                course_gift: this.course_gift
              }
            }
            if (this.courseId && this.isChange) {
              editCourse({ course_id: this.courseId, ...payload }).then(
                response => {
                  if (response.code === 200) {
                    this.msgSuccess(response.msg)
                    this.active++
                  } else {
                    this.msgError(response.msg)
                  }
                }
              )
            } else if (this.courseId) {
              this.active++
            } else {
              addCourse(payload).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.courseId = response?.data
                  this.active++
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          } else {
            return
          }
        })
      } else if (this.active === 2) {
        if (this.courseId) {
          getSave({
            link_type: 1,
            obj_id: this.courseId
          }).then(res => { })
        }
        this.$router.push('/admin/sys-course/online')
      }
    },
    parentSay(msg) {
      this.chapterData = this.chapterData.map(item =>
        item.name === msg.name ? msg : item
      )
    },
    handleAvatarSuccess(res) {
      this.courseForm.cover = res.data.full_path
    },
    handleAvatarOutline(res, type) {
      if (type === 'outline') {
        this.courseForm.outline.push(res.data.full_path)
      } else {
        this.courseForm.introduction.push(res.data.full_path)
      }
    },
    handleAvatarContacts(res) {
      this.lecturerForm.contacts = res.data.full_path
    },
    beforeAvatarUpload(file) {
      // const isLt2M = file.size / 1024 / 1024 < 2.0
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2M!')
      // }
      return !isJPG
    },
    handleRemove(file, type) {
      if (type === 'outline') {
        this.courseForm.outline = this.courseForm.outline.filter(
          (item, index) => file !== index
        )
      } else {
        this.courseForm.introduction = this.courseForm.introduction.filter(
          (item, index) => file !== index
        )
      }
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    },

    beforeRemove(event, file) {
      event.stopPropagation()
      return this.$confirm(`确定移除 ${file}？`)
        .then(() => {
          this.courseForm.audition_link = ''
          this.courseForm.audition_course_name = ''
          this.percentage = 0
        })
        .catch(() => { })
    },
    playVideo(url) {
      this.showVideo = true
      this.playUrl = url
    },
    handleHideModal() {
      this.playUrl = ''
      this.showVideo = false
    },
    clickTopic(value, idList) {
      this.topicType = value
      this.visibleTopic = true
      this.idList = idList
    },
    cancelTopic() {
      this.visibleTopic = false
    },
    submitFormTopic(id) {
      console.log(id, '//......id');
      if (id.length > 0 && this.courseId) {
        this.isChange = true
      }
      this.visibleTopic = false
      if (this.topicType === 'question_bank') {
        this.questionBankNumber = id
        this.course_gift[0].obj_ids = id.join()
      } else {
        this.examinationNumber = id
        this.course_gift[1].obj_ids = id.join()
      }
    },
    async httpUpload(files) {
      const { file } = files
      try {
        // 判断扩展名
        const tmpcnt = files.file.name.lastIndexOf('.')
        const exname = files.file.name.substring(tmpcnt + 1)
        const client = clients()
        const names = ['wav', 'mp4']
        if (names.indexOf(exname) < 0) {
          this.$message.error('不支持的格式!')
          return
        }
        this.loading = true
        const imgUrl = 'http://image.twzxjy.com'
        const fileName = `static/uploadfile/${getNowDate()}/${files.file.uid
          }.${exname}`

        // 依次填写Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。Object完整路径中不能包含Bucket名称。
        // 如果本地文件的完整路径中未指定本地路径（例如examplefile.txt），则默认从示例程序所属项目对应本地路径中上传文件。
        await client.multipartUpload(fileName, file, {
          progress: (p, cpt, res) => {
            // 获取分片上传进度、断点和返回值。
            this.percentage = (Math.floor(p * 100) / 100) * 100
            if (p === 1) {
              this.loading = false
            }
          },
          parallel: 5, // 并发上传的分片数量
          partSize: 1024 * 1024 * 20,
          // headers,
          // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
          meta: {
            year: 2020,
            people: 'test'
          },
          mime: file.type // 上传文件类型
        })
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        const head = await client.head(fileName)
        if (head.status === 200) {
          this.$set(this.courseForm, 'audition_link', `${imgUrl}/${fileName}`)
          this.$set(this.courseForm, 'audition_course_name', file.name)
        }
      } catch (e) {
        if (e.code === 'ConnectionTimeoutError') {
          console.log('TimeoutError')
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  .el-progress {
    line-height: 2.3;
  }
}
</style>
